package team06;

import hockey.api.*;

public class LeftForwarder extends Player {
	@Override
	public String getName() {
		return "Mr. Pink";
	}

	@Override
	public int getNumber() {
		return 3;
	}

	@Override
	public boolean isLeftHanded() {
		return true;
	}

	private double avgSpeed = 0;
	private double speedAlpha = 0.7;
	
	@Override
	public void step() throws Exception {
		int goalPosX = 2600;
		int goalPosY = 0;
		
		// Speed running average
		avgSpeed = (1 - speedAlpha)*avgSpeed + speedAlpha*getSpeed();
		
		//Do we have the puck?:
		if ( hasPuck() ) {
			skate( goalPosX, goalPosY, 1000 ); // Go for the goal
			turn( goalPosX, goalPosY, 250 ); // Turn towards the goal (What is a good turn speed?)
			
			
			// Angle and shoot code from TriggerHappy sample
			double goalDist = Util.dist( goalPosX - getX(), goalPosY - getY() );
			double goalAngle = Math.abs(Util.dangle(getHeading(),
				     					Util.datan2(goalPosY - getY(),
				     							goalPosX - getX())));
			
			// If we are close enough and are facing the goal, shoot
			if ( goalDist < 1500 && goalAngle < 90 && getX() < goalPosX) {
				int target = (int)( Math.random( ) * 200 )-100;
				shoot( goalPosX, target, 10000 ); // Shoot!
			}
		} else if ( getPuck().getX() < 750 && getX() > 850 ) { // Are we at risk of being offside?
				turn( 180, 700 );
				skate( 1000 );
				return;
		} else if ( getPuck().getX() < -850 ) {
			skate( -900, 0, 400 );
			return;
		} else if ( avgSpeed < 200 && getTurnSpeed() < 10 ) { // Have we gotten stuck?
			// Try to skate away
			turn( getHeading() + 180, 700 );
			skate( 1000 );
		} else {
			// Find who has the puck (that's not a goalkeeper)
			IPlayer puckHolder = null;
			for ( int index = 0; index < 12; index++ )
				if ( index != 0 && index != 6 &&
					getPlayer( index ).hasPuck() ) {
					puckHolder = getPlayer( index );
					break;
				}
			
			if ( puckHolder == null )
			{
				// Who on our team is the closest to the puck
				IPlayer nearestToPuck = null;
				double minDist = Double.MAX_VALUE;
				for ( int index = 0; index < 12; index++ ) {
					IPlayer player = getPlayer( index );
					if ( player.isOpponent() )
						continue;
					
					double dist = Util.dist( player, getPuck() );
					
					if ( dist < minDist ) {
						minDist = dist;
						nearestToPuck = player;
					}
				}
				
				// If we are the nearest player or no one on our team
				// is within three meters of the puck.
				if ( nearestToPuck == this || minDist > 300 ) {
					skate( getPuck(), 1000 );
				} else {
					// Turn towards the puck and move slowly
					turn( getPuck(), 700 );
					skate( 200 );
				}
			} else if ( puckHolder.isOpponent() )
			{
				//Go towards puck
				skate( getPuck(), 1000 );
			} else {
				// Try to match speed and heading of the holder
				int heading = puckHolder.getHeading();
				int speed = puckHolder.getSpeed();
				
				skate( speed );
				turn( heading, 700 );
			}	
		}
	}
}
